//
//  RatingControl.swift
//  TestSwift3
//
//  Created by ficow on 15/8/16.
//  Copyright © 2016年 ficow. All rights reserved.
//

import UIKit

class RatingControl: UIView {

    let spacing = 5
    let starCount = 5
    let selfHeight:CGFloat = 44
    var rating = 0{
        didSet{
            setNeedsLayout()
        }
    }
    var ratingButtons = [UIButton]()
    let filledStarImg = UIImage(named: "filledStar")
    let emptyStarImg = UIImage(named: "emptyStar")
    // it's different in iOS 10
    override var intrinsicContentSize: CGSize{
        frame.size.height = selfHeight
        let buttonSize = Int(frame.size.height)
        let width = (buttonSize * starCount) + (spacing * (starCount - 1))
        
        return CGSize(width: width, height: buttonSize)
    }
    
    required init?(coder aDecoder: NSCoder) {  //init?
        super.init(coder: aDecoder)
        
        self.isUserInteractionEnabled = true;
        
        for _ in 0..<starCount{
            let button = UIButton()
            button.adjustsImageWhenHighlighted = false
            button.addTarget(self,action:#selector(ratingButtonTapped(_:)),for:.touchUpInside)
            button.setImage(emptyStarImg, for: .normal)
            button.setImage(filledStarImg, for: .selected)
            button.setImage(filledStarImg, for: [.selected,.highlighted])
            ratingButtons += [button] //? += [instanceName]
            addSubview(button)
        }
        
        
    }
    
    override func layoutSubviews() {
        let buttonSize = Int(frame.size.height)
        
        var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
        for (index,button) in ratingButtons.enumerated() {
            buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing))
            button.frame = buttonFrame
        }
        updateButtonSelectionStates()
    }
    
    func ratingButtonTapped(_ button:UIButton){
        rating = ratingButtons.index(of: button)! + 1
        updateButtonSelectionStates()
    }
    
    func updateButtonSelectionStates(){
        for(index,button) in ratingButtons.enumerated(){
            button.isSelected = index < rating
        }
    }

}
